<?php

namespace App\Http\Controllers\home;

use App\Http\Model\Cart;
use App\Http\Model\Gorder;
use App\Http\Model\Order;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Input;

/***
 * Class OrderController 商品订单控制器
 * @package App\Http\Controllers\home
 */
class OrderController extends Controller
{
    /**
     * 加载订单视图
     */
    public function order(){
        /** 获取购物车中所有商品 */
        /** 检测当前会员是否登陆 */
        /** 判断当前用户是否登陆 */
        $uid = Cookie::get('id');
        if(!$uid){
            /** 跳转登陆页面 */
            /** 记录当前请求action */
            session(['backUrl'=>"order"]);
            return redirect('login');
        }
        /** 获取当前会员购物车中的商品 */
        $goods_list = Cart::where('user_id',$uid)->get();
        /** 计算商品总价 */
        $total = 0;
        foreach($goods_list as $goods){
            $total += $goods->goods_price * $goods->goods_num;
        }
        /** 加载订单视图 */
        return view('home.order.order',compact('goods_list','total'));
    }

    /**
     * 生成订单
     */
    public function toOrder(){
        $input = Input::except('_token');
        $uid = Cookie::get('id');
        /**整合数据*/
        $order_id = $this -> getOrderSn();
        $input['uid'] =  $uid;
        $input['order_num'] = $order_id;
        $input['order_total'] = $this -> getTotal($uid);
        $input['add_time'] = time();
        /**生成订单*/
        if(!Order::insert($input)){
           die('数据插入失败!');
        }
        /**插入订单商品信息*/
        $goods_list = Cart::where('user_id',$uid)->get();
        foreach($goods_list as $goods){
            $temp['order_id'] = $order_id;
            $temp['goods_id'] = $goods->goods_id;
            $temp['goods_num'] = $goods->goods_num;
            Gorder::insert($temp);
        }
        /**清空购物车商品*/
        Cart::where('user_id',$uid)->delete();
        /**跳转支付页面*/
        return redirect('pay/'.$order_id);
    }

    /***
     * 生成订单号 2016 10 02 随机7位
     */
    public function getOrderSn(){
        return date('Ymd') . mt_rand(1111111,9999999);
    }

    /**
     * 获取商品总价
     */
    public function getTotal($uid){
        /** 获取当前会员购物车中的商品 */
        $goods_list = Cart::where('user_id',$uid)->get();
        /** 计算商品总价 */
        $total = 0;
        foreach($goods_list as $goods){
            $total += $goods->goods_price * $goods->goods_num;
        }
        return $total;
    }
}
